<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.name" placeholder="任务名称" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                查询
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                @click="handleCreate">
                新建群发
            </el-button>
            <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="alltypes">
                批量执行
            </el-button> -->
        </div>
        <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
            style="width: 100%;" @sort-change="sortChange">
            <el-table-column label="任务ID" prop="id" sortable="custom" align="center" width="120"
                :class-name="getSortClass('id')">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column label="任务名称" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.rwname }}</span>
                </template>
            </el-table-column>
            <el-table-column label="任务数量" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.rwnum }}</span>
                </template>
            </el-table-column>

            <el-table-column label="发送内容" width="350px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.content }}</span>
                    <span v-if="row.lxtype == 5">{{ row.VcardName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="发送类型" width="120px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.lxtype == 1 ? '文本任务' : row.lxtype == 2 ? '图片任务' : row.lxtype == 5 ? '卡片任务' : '其他任务'
                        }}</span>
                </template>
            </el-table-column>

            <el-table-column label="创建时间" width="150px" align="center">
                <template slot-scope="{row}">
                    <el-tag>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}') }} </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="状态" class-name="status-col" width="100">
                <template slot-scope="{row}">
                    <el-tag :type="row.status | statusFilter">
                        {{ row.status == 1 ? '待执行' : row.status == 2 ? '执行成功' : '失败' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                    <el-button type="primary" size="mini" @click="handleFetchXq(row, $index)">
                        任务详情
                    </el-button>
                    <el-button type="primary" v-if="row.status != 1" size="mini" @click="handleFetchPv(row, $index)">
                        任务日志
                    </el-button>
                    <el-button size="mini" v-if="row.status == 1" type="danger" @click="handleDelete(row, $index)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px"
                style="width: 600px; margin-left:20px;">
                <el-form-item label="导入发送账号" prop="username">
                    <upload-excel-component :on-success="handleSuccess1" :before-upload="beforeUpload" />
                    <el-collapse>
                        <el-collapse-item title="已导入号码" name="1">
                            <div>{{ temp.pcontent }}</div>
                        </el-collapse-item>
                    </el-collapse>
                </el-form-item>
                <el-form-item label="导入接受账号" prop="username">
                    <upload-excel-component :on-success="handleSuccess2" :before-upload="beforeUpload" />
                    <el-collapse>
                        <el-collapse-item title="已导入号码" name="1">
                            <div>{{ temp.fcontent }}</div>
                        </el-collapse-item>
                    </el-collapse>
                </el-form-item>
                <el-form-item label="系统类型">
                    <el-radio-group v-model="temp.lxtype" @input="getqhuan">
                        <el-radio :label="1">文本</el-radio>
                        <el-radio :label="2">图片</el-radio>
                        <el-radio :label="4">语音</el-radio>
                        <el-radio :label="5">卡片</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="文本消息" v-if="temp.lxtype == 1">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容"
                        v-model="temp.content">
                    </el-input>

                    <!-- <Tinymce ref="editor" v-model="temp.content" :height="60" :width="600" /> -->

                </el-form-item>
                <el-form-item label="图片消息" v-if="temp.lxtype == 2">
                    <el-select v-model="temp.content" placeholder="请选择">
                        <el-option v-for="item in zylist" :key="item.id" :label="item.name" :value="item.id"
                            value-key="id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="语音消息" v-if="temp.lxtype == 4">
                    <el-select v-model="temp.content" placeholder="请选择">
                        <el-option v-for="item in zylist" :key="item.id" :label="item.name" :value="item.id"
                            value-key="id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="卡片消息" v-if="temp.lxtype == 5">
                    <el-input placeholder="请输入卡片名称" v-model="txemp.VcardName">
                    </el-input>
                    <!-- <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入卡片内容"
                        v-model="temp.content">
                    </el-input> -->
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
                    发起任务
                </el-button>
            </div>
        </el-dialog>







        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogPvVisible">
            <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
                <el-table-column label="手机号" width="150px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.phone }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.content }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="json数据" width="250px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.jsonall }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="时间" width="150px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>



        <!-- 详情任务列表 -->
        <el-dialog title="任务详情" :visible.sync="listPvVisible" :width="'70%'">
            <el-table :data="pvDatalist" border fit highlight-current-row style="width: 100%">
                <el-table-column label="发送账号" width="130px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.phone }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="接受账号" width="130px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.rphone }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="发送内容" width="220px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.content }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="执行状态" width="120px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.status == 1 ? '待执行' : row.status == 2 ? '成功' : '失败' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="json数据" width="250px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.jsonall }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="时间" width="120px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>



    </div>
</template>

<script>
import {
    fetchList, fetchPv, updateArticle, getDel, getfzList, getbqList, getZylist, getrwzxlist, getAddAll, getrwdetailList
} from '@/api/drqfrw'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Tinymce from '@/components/Tinymce'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import UploadExcelComponent from '@/components/UploadExcel/maxindex.vue'
const statusOptions = [
    { key: 1, display_name: '正常' },
    { key: 2, display_name: '暂停' },
    { key: 3, display_name: '封禁' },
    { key: 4, display_name: '异常' }
]

export default {
    name: 'ComplexTable',
    components: { Pagination, UploadExcelComponent, Tinymce },
    directives: { waves },
    filters: {
        statusFilter(status) {
            const statusMap = {
                1: 'info',
                2: 'success',
                3: 'danger'
            }
            return statusMap[status]
        },
        typeFilter(type) {
            return calendarTypeKeyValue[type]
        }
    },
    data() {
        return {
            tableKey: 0,
            list: null,
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                types: 3,
                name: ''
            },
            statusOptions,
            showReviewer: false,
            temp: {
                id: undefined,
                lxtype: 1,
                pcontent: '',
                fcontent: '',
                content: '',
                VcardName: ''
            },
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: 'Edit',
                create: 'Create',
                logs: 'Logs'
            },
            dialogPvVisible: false,
            listPvVisible: false,
            pvDatalist: [],
            pvData: [],
            fenzulist: [],
            bqianlist: [],
            zylist: [],
            multipleSelection: [],
            rules: {
                type: [{ required: true, message: 'type is required', trigger: 'change' }],
                title: [{ required: true, message: 'title is required', trigger: 'blur' }]
            },
            downloadLoading: false
        }
    },
    created() {
        this.getList()
        this.getfzallt()
        this.getbqallt()
        this.getZylists(1)
    },
    methods: {
        getqhuan(e) {
            console.log(e)
            if (e == 2) {
                this.getZylists(1)
            }
            if (e == 4) {
                this.getZylists(4)
            }
        },
        beforeUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 1
            if (isLt1M) {
                return true
            }
            this.$message({
                message: 'Please do not upload files larger than 1m in size.',
                type: 'warning'
            })
            return false
        },
        handleSuccess1({ results, header }) {
            console.log(results)
            console.log(header)
            let listall = results
            let arr = []
            listall.forEach(function (item, index) {
                arr.push(item.号码)
            });
            let arrs = arr.join(",");
            //输出数组的每一个元素
            this.temp.pcontent = arrs
        },
        handleSuccess2({ results, header }) {
            console.log(results)
            console.log(header)
            let listall = results
            let arr = []
            listall.forEach(function (item, index) {
                arr.push(item.号码)
            });
            let arrs = arr.join(",");
            //输出数组的每一个元素
            this.temp.fcontent = arrs
        },
        alltypes() {
            let list = this.multipleSelection
            let arr = []
            list.forEach(function (item, index) {
                console.log(item); //输出数组的每一个元素
                if (item.logonstatus != 2) {
                    arr.push(item.id)
                }
            });
            if (arr.length > 0) {
                //进行登陆操作
                let temp = {
                    ids: arr.join(",")
                }
                this.listLoading = true
                getrwzxlist(temp).then(response => {
                    this.$notify({
                        title: 'Success',
                        message: 'Created Successfully',
                        type: 'success',
                        duration: 2000
                    })
                    this.getList();
                })
            }
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log('导入数据', this.multipleSelection)
        },
        getfzallt() {
            getfzList().then(response => {
                this.fenzulist = response.data.list
            })
        },
        getZylists(types) {
            let data = {
                types: types
            }
            getZylist(data).then(response => {
                this.zylist = response.data.list
            })
        },
        getbqallt() {
            getbqList().then(response => {
                this.bqianlist = response.data.list
            })
        },

        getList() {
            this.listLoading = true
            fetchList(this.listQuery).then(response => {
                console.log(response.data)
                this.list = response.data.list
                this.total = response.data.count
                this.listLoading = false
            })
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleModifyStatus(row, status) {
            this.$message({
                message: '操作Success',
                type: 'success'
            })
            row.status = status
        },
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'id') {
                this.sortByID(order)
            }
        },
        sortByID(order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+id'
            } else {
                this.listQuery.sort = '-id'
            }
            this.handleFilter()
        },
        resetTemp() {
            this.temp = {
                id: undefined,
                fcontent: '',
                pcontent: '',
                lxtype: 1,
                content: '',
                VcardName: ''
            }
        },
        handleCreate() {
            this.resetTemp()
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        createData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    getAddAll(this.temp).then(res => {
                        this.dialogFormVisible = false
                        this.$notify({
                            title: '信息通知',
                            message: '当前账号未在系统中注册的 无法创建任务',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList();
                    })
                }
            })
        },
        handleUpdate(row) {
            this.temp = Object.assign({}, row) // copy obj
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    const tempData = Object.assign({}, this.temp)
                    updateArticle(tempData).then(() => {
                        const index = this.list.findIndex(v => v.id === this.temp.id)
                        this.list.splice(index, 1, this.temp)
                        this.dialogFormVisible = false
                        this.$notify({
                            title: 'Success',
                            message: 'Update Successfully',
                            type: 'success',
                            duration: 2000
                        })
                    })
                }
            })
        },
        handleDelete(row, index) {
            let temp = {
                id: row.id
            }
            getDel(temp).then(() => {
                this.$notify({
                    title: 'Success',
                    message: 'Created Successfully',
                    type: 'success',
                    duration: 2000
                })
            })
            this.list.splice(index, 1)
        },
        //任务详情
        handleFetchXq(row, index) {
            getrwdetailList({ id: row.id }).then(response => {
                this.pvDatalist = response.data.list
                this.listPvVisible = true
            })
        },
        //任务日志
        handleFetchPv(row, index) {
            fetchPv({ id: row.id, lxtype: row.lxtype }).then(response => {
                this.pvData = response.data.list
                this.dialogPvVisible = true
            })
        },
        getSortClass: function (key) {
            const sort = this.listQuery.sort
            return sort === `+${key}` ? 'ascending' : 'descending'
        }
    }
}
</script>
